import { Component } from '/src/components/component/component.js';
import { TemplateManager } from '/src/util/templatemanager/templatemanager.js'

export class BaseChartConfig extends Component {
    constructor(container, options) {
        super(container, options);
        this.currentType = options.chartType || 'sequence';
        this.$baseConfigContainer = options.baseConfigContainer ? $(options.baseConfigContainer) : $('#baseConfigContainer');
        this.$seriesConfigContainer = options.seriesConfigContainer ? $(options.seriesConfigContainer) : $('#seriesConfigContainer');
    }

    async generateBaseConfigForm() {
        this.$baseConfigContainer.empty();
        try {
            const html = await TemplateManager.loadTemplate('/src/components/component/chart/config/chart-form-config.html', {
                title: this.data.title,
                cid: this.cid
            });
            this.$baseConfigContainer.append(html);

            const $input = $(`#chartName`);
            $input.on('input', (e) => {
                const newTitle = e.target.value;
                this.data.title = newTitle;
                this.trigger('configChanged', { title: newTitle });
            });

            const $typeSelect = $(`#type-${this.cid}`);
            $typeSelect.val(this.currentType);
            $typeSelect.off('change'); // 先解绑之前的事件
            $typeSelect.on('change', e => {
                this.currentType = e.target.value;
                this.trigger('chartTypeChanged', { chartType: e.target.value });
            });
        } catch (error) {
            console.error('加载基础配置模板失败', error);
        }
    }

    async generateSeriesConfigForm() {
    }
    
    // 通用的配置更新方法
    updateSeriesConfig(index, config) {
        if (this.data.series && this.data.series[index]) {
            Object.assign(this.data.series[index], config);
            if (this.data.legend && Array.isArray(this.data.legend) && this.data.legend[index] !== undefined) {
                if (config.name !== undefined) {
                    this.data.legend[index] = config.name;
                }
            }
            this.render();
            this.trigger('configChanged', { seriesIndex: index, config });
        }
    }
}